"""
卧槽 这个轮子好烂 看我造个更烂的
"""
import socket
import time


class MyServer:

    def __init__(self, application=None, host='localhost', port='8080'):
        self.application = application
        server = socket.socket()
        server.bind((host, port))
        server.listen(10)
        self.server = server
        print('server is running...')

    def start_response(self, status, response_headers, exc_info=None):
        """
        :params status: 指HTTP的状态字符串如`200 OK`,`404 Not Found`
        :params response_headers: 是一个形如(header_name, header_value)的元组列表
        :params exc_info: sys.exc_info()返回的 tuple: (type, value, traceback)
        :return write()
        """
        data = f'{self.protocol} {status}\r\n'
        for k, v in response_headers:
            data += f'{k}:v\r\n'
        data += '\n'

        self.response_data = data.encode('utf=8')

        return 'write()'

    def run(self):
        while True:
            client_socket, client_address = self.server.accept()
            request = client_socket.recv(1024)

            messages = request.decode('utf-8').split('\r\n')
            method, path, self.protocol = messages.pop(0).split(' ')
            environ = {
                'REQUEST_METHOD': method,
                'SCRIPT_NAME': path,
                'SERVER_PROTOCOL': self.protocol,
            }
            for message in messages:
                m = message.split(': ')
                print(m)
                # environ[k] = v

            response_data = b''

            result = self.application(environ, self.start_response)
            for content in result:
                resp = response_data + content
                time.sleep(1)
                client_socket.sendall(resp)
            client_socket.close()
